package com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business

import android.app.Activity
import android.util.Log
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.bean.ConfigResultBean
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.MyHandler
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ADConfig
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadGoogleAd
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadIronSourceAd
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.GoogleRewardListener
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.IronSourceRewardListener
import java.util.*
import java.util.concurrent.atomic.AtomicInteger

class ADRewardManager private constructor() : GoogleRewardListener, IronSourceRewardListener {
    // UnityRewardListener
    private var adQueue: PriorityQueue<ConfigResultBean.AdInfo>? = null // 存储AdInfo
    private val rewardList =
        Collections.synchronizedList(ArrayList<ArrayList<ConfigResultBean.AdInfo>>())    // 存储两组广告ID

    // 高并发环境下 i++无法保证线程安全
    private var allGroupSize = 0       // 总共有几组 (目前2组 2-2)
    private var rCurrentInGroupSize = 0// 当前使用这一组大小 (2个)

    @Volatile
    private var rCurrentGroupIndex = AtomicInteger(0) // 当前请求的是第几组

    private var isShow = false

    @Volatile
    private var errorNum = AtomicInteger(0)

    @Volatile
    private var successNum = AtomicInteger(0)

    companion object {
        val mInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            ADRewardManager()
        }
    }

    override fun onGoogleRewardFailed() {
        errorNum.addAndGet(1)
        isRequestNextID(rCurrentGroupIndex.get())
    }

    override fun onIronSourceRewardFailed() {
        errorNum.addAndGet(1)
        isRequestNextID(rCurrentGroupIndex.get())
    }

//    override fun onUnityRewardFailed(error: String) {
//        errorNum.addAndGet(1)
//        isRequestNextID(rCurrentGroupIndex.get())
//    }

    override fun onGoogleRewardLoad(bean: ConfigResultBean.AdInfo) {
        successNum.set(1)
        createAndAdd(bean)
    }

    override fun onIronSourceRewardLoad(bean: ConfigResultBean.AdInfo) {
        successNum.set(1)
        createAndAdd(bean)
    }

//    override fun onUnityRewardLoad(bean: ConfigResultBean.AdInfo) {
//        successNum.set(1)
//        createAndAdd(bean)
//    }

    @Synchronized
    fun createAndAdd(bean: ConfigResultBean.AdInfo) {
        if (adQueue == null) {
            adQueue = createQueue(rCurrentInGroupSize)
        }
        adQueue!!.offer(bean)
    }

    @Synchronized
    private fun isRequestNextID(index: Int) {
        if (rewardList.size > 0) {
            if (errorNum.get() == rewardList[if (index < rewardList.size) index else 0].size) {
                errorNum.set(0)
                isRequestNextGroup(index)
            }
        }
    }

    private fun isRequestNextGroup(index: Int) {
        val nextIndex = index + 1
        if (allGroupSize > 0) {
            if (nextIndex < allGroupSize) {
                rCurrentInGroupSize = rewardList[nextIndex].size
                if (adQueue == null) adQueue = createQueue(rCurrentInGroupSize)
                rewardGroupRequest(nextIndex)
            }
        }
    }

    fun showRewardAD(
        placement: String,
        activity: Activity,
        position: Int,
        type: String
    ): Boolean {
        val time: Int =
            ((System.currentTimeMillis() - AppSettingManager.readLong(
                "rewardTime",
                0
            )) / 1000f).toInt()
        if (time in 1..199) {
            AppSettingManager.saveLong(System.currentTimeMillis(), "rewardTime")
        }
        FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_SHOULD_DISPLAY, "type", type)

        if (adQueue == null) { // splash里还没加载完就展示了
            adQueue = createQueue(rCurrentInGroupSize)
            return false
        }

        if (rewardList.size > 0) {
            if (adQueue!!.isEmpty() && rCurrentGroupIndex.get() >= rewardList.size) {
                FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Reward", "None_$time")
                rewardGroupRequest(0)
                return false
            } else {
                val adBean = adQueue!!.poll()
                if (adBean != null) {
                    when (adBean.advertiser) {
                        ADConfig.ADMOB -> {
                            isShow = LoadGoogleAd.mInstance.showRewardedVideoAd(
                                adBean,
                                placement,
                                activity,
                                position, time
                            )
                        }
                        ADConfig.IS -> {
                            isShow = LoadIronSourceAd.mInstance.showRewardedVideoAd(
                                adBean,
                                placement,
                                position, time
                            )
                        }
//                        ADConfig.UNITY -> {
//                            isShow = LoadUnityAd.mInstance.showRewardedVideoAd(
//                                placement,
//                                activity,
//                                position
//                            )
//                        }
                    }
                } else {
                    FlurryEventUtil.putDataToEvent(
                        EventType.TYPE_IS_READY,
                        "Reward",
                        "None_$time"
                    )
                }
            }

            // 所有组别都失败下一次展示从头开始请求
            if (!isShow && adQueue!!.isEmpty() && rCurrentGroupIndex.get() >= rewardList.size - 1) {
                rewardGroupRequest(0)
            }

            //组内有任意一个请求成功从头开始请求
            if (adQueue!!.isEmpty() && successNum.get() > 0) {
                successNum.set(0)
                errorNum.set(0)
                rewardGroupRequest(0)
            }
        } else {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Reward", "None_$time")
        }

        return isShow
    }

    private var mActivity: Activity? = null
    fun initConfig(activity: Activity, bean: ConfigResultBean.ConfigResultBeanData) {
        mActivity = activity
        LoadGoogleAd.mInstance.setGoogleRewardListener(this)
        LoadIronSourceAd.mInstance.setIronSourceRewardListener(this)
//        LoadUnityAd.mInstance.setUnityRewardListener(this)
        rewardList.clear()
        rewardList.addAll(bean.ADID.Reward)
        allGroupSize = rewardList.size

        rCurrentInGroupSize = if (rewardList.isNotEmpty()) rewardList[0].size else 0
        AppSettingManager.saveLong(System.currentTimeMillis(), "rewardTime")
        rewardGroupRequest(0)
    }

    private fun createQueue(size: Int): PriorityQueue<ConfigResultBean.AdInfo> {
        var reSize = 2
        if (size >= 1) {
            reSize = size
        }
        return PriorityQueue(reSize,
            Comparator<ConfigResultBean.AdInfo> { s1, s2 ->
                s2.cpminfo.toInt() - s1.cpminfo.toInt()
            })
    }

    @Synchronized
    private fun rewardGroupRequest(index: Int) {
        if (rewardList.size > 0) {
            rCurrentGroupIndex.set(index)
            Log.e("RwsTestIndex", rCurrentGroupIndex.get().toString())
            MyHandler.instance?.let {
                it.post {
                    rewardList[if (index < rewardList.size) index else 0].forEach { it ->
                        when (it.advertiser) {
//                            ADConfig.ADMOB -> {
//                                LoadGoogleAd.mInstance.initRewardAD(it)
//                            }
                            ADConfig.IS -> {
                                LoadIronSourceAd.mInstance.initIsRewardAd(mActivity!!, it)
                            }
//                            ADConfig.UNITY -> {
//                                LoadUnityAd.mInstance.initRewardAD(it)
//                            }
                        }
                    }
                }
            }
        }
    }

//    @Synchronized
//    fun getRewardFirst() {
//        if (rewardList.size > 0) {
//            rewardList[0].forEach { it ->
//                when (it.advertiser) {
//                    ADConfig.ADMOB -> {
//                        LoadGoogleAd.mInstance.initRewardAD(it)
//                    }
//                }
//            }
//        }
//    }

}